package com.wecan.gateway.filter;

import com.wecan.base.enums.ResultStatus;
import com.wecan.base.model.Result;
import com.wecan.gateway.constant.PropertyConstant;
import com.wecan.gateway.properties.GatewayProperties;
import com.wecan.gateway.utils.WebFluxUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

/**
 * @Author liuzhihao
 * @Date 2022.03.09
 * @Version ${version}
 * @Description ${description}
 */
@Component
@Slf4j
@RefreshScope
public class PubAppFilter implements WebFilter, Ordered {

    @Autowired
    private GatewayProperties gatewayProperties;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getPath().toString();
        if (gatewayProperties.isPubApp() && (path.startsWith("/client") || path.startsWith("/waiter") || path.startsWith("/oauth"))) {
            return WebFluxUtils.writeJsonResponse(exchange.getResponse(), new Result().type(ResultStatus.PUB_APP).status(HttpStatus.SC_BAD_REQUEST));
        }
        // 如果外部调用sendmessage则不允许
        if (path.startsWith("/cim/message") || path.startsWith("/oauth/inside")) {
            return WebFluxUtils.writeJsonResponse(exchange.getResponse(), new Result().type(ResultStatus.ACCESS_DENIED).status(HttpStatus.SC_BAD_REQUEST));
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return FilterOrder.PUB_APP_FILTER_ORDER;
    }
}
